package com.pet.platform.security;

import com.pet.platform.entity.User;
import com.pet.platform.service.UserService;
import com.pet.platform.util.JwtUtil;
import com.pet.platform.util.SecurityUtils;
import com.pet.platform.util.SecurityUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationFilter.class);

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private UserService userService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        try {
            // 尝试从请求中提取JWT令牌
            String jwt = getJwtFromRequest(request);
            
            if (StringUtils.hasText(jwt)) {
                logger.debug("JWT token found in request: {}", request.getRequestURI());
                try {
                    // 尝试提取用户名
                    String username = jwtUtil.extractUsername(jwt);
                    
                    if (username != null) {
                        logger.debug("Username extracted from token: {}", username);
                        
                        // 尝试加载用户并设置认证
                        try {
                            UserDetails userDetails = userService.loadUserByUsername(username);
                            User user = userService.findByUsername(username);
                            
                            if (user != null) {
                                // 设置认证信息
                                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                                        userDetails, null, userDetails.getAuthorities());
                                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                                
                                // 更新安全上下文
                                SecurityContextHolder.getContext().setAuthentication(authentication);
                                
                                // 设置当前用户
                                SecurityUtils.setLoginUser(user);
                                SecurityUtil.setLoginUser(user);
                                logger.debug("Authentication successful for user: {}", username);
                            }
                        } catch (Exception e) {
                            logger.warn("Failed to authenticate user: {}", e.getMessage());
                        }
                    }
                } catch (Exception e) {
                    logger.warn("Failed to process JWT token: {}", e.getMessage());
                }
            } else {
                logger.debug("No JWT token found in request: {}", request.getRequestURI());
                
                // 即使没有令牌，也设置一个匿名用户认证，允许请求通过
                if (SecurityContextHolder.getContext().getAuthentication() == null) {
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                            "anonymousUser", null, Collections.singletonList(new SimpleGrantedAuthority("ROLE_ANONYMOUS")));
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                    logger.debug("Set anonymous authentication for request: {}", request.getRequestURI());
                }
            }
        } catch (Exception e) {
            logger.error("Error in JWT authentication filter: {}", e.getMessage());
            // 捕获任何异常，但不要阻止请求
        }
        
        // 允许请求继续
        filterChain.doFilter(request, response);
    }

    private String getJwtFromRequest(HttpServletRequest request) {
        // 尝试从Authorization头部提取令牌
        String bearerToken = request.getHeader("Authorization");
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }
} 